const fs = require('fs');
const path = require('path');
const CONFIG = require('../config');
const Color = require('./color');

class Logger extends Color {

  constructor(filePath) {
    super();
    this.filePath = filePath;
    const fileName = path.basename(this.filePath);
    const file = this.filePath.replace(fileName, '');
    // 递归创建目录 node >= 10.14.1
    !fs.existsSync(file) &&
      fs.mkdirSync(
        file, {
          recursive: true
        }
      );
    this.init();
  }

  init() {
    try {
      const now = Logger.getFormatDate();
      this.stream && fs.rename(this.filePath, this.filePath + '.' + this.suffix, () => {});
      this.stream && this.stream.end();
      this.suffix = now.date;
      this.stream = fs.createWriteStream(this.filePath, {
        flags: 'a',
        encoding: 'utf-8'
      });
    } catch (error) {
      console.error('Logger重置异常,请确保目录存在: %s', error);
      throw error;
    }
  }

  write(msg) {
    try {
      const now = Logger.getFormatDate();
      now.date !== this.suffix && this.init();
      msg = this.green(now.date + ' ' + now.hour + ' ') + msg;
      !CONFIG.IS_PROD && console.log(msg);
      return this.stream.write(msg);
    } catch (error) {
      console.error(`StreamWrite: %s`, error);
    }
  }

  warn(msg) {
    msg = this.yellow(' [WARN] ' + msg + '\n');
    return this.write(msg);
  }

  info(msg) {
    msg = this.green(' [INFO] ' + msg + '\n');
    return this.write(msg);
  }

  error(msg) {
    msg = this.red(' [ERROR] ' + msg + '\n');
    return this.write(msg);
  }

  static getFormatDate() {
    const now = new Date(),
      year = now.getFullYear(),
      month = now.getMonth() + 1,
      day = now.getDate(),
      hour = now.getHours(),
      minute = now.getMinutes(),
      second = now.getSeconds(),
      mi = now.getMilliseconds();
    return {
      date: year + '.' + month + '.' + day,
      hour: hour + ':' + minute + ':' + second + ',' + mi
    };
  }

}

module.exports = new Logger(CONFIG.LOGGER.loggerDir);